﻿using System.Data;
using Microsoft.SharePoint;

namespace QueryDemo.ResultProviders
{
	/// <summary>
	/// For-loop over an SPListItemCollection.
	/// </summary>
	public class ForLoopResultProvider : BaseResultProvider
	{
		private DataTable _resultsTable;

		/// <summary>
		/// Sets properties related to use of the query within the web part.
		/// </summary>
		public ForLoopResultProvider()
		{
			TypeOfQuery = QueryType.ForLoop;
			QueryName = "For Loop";
		}

		public override bool CrossSiteCapable
		{
			get { return false; }
		}

		public override void Init()
		{
			_resultsTable = new DataTable();
			foreach (string field in ViewFields)
			{
				DataColumn column = _resultsTable.Columns.Add();
				column.ColumnName = field;
				// TODO: Change column type depending on, er, type
			}
		}

		public override DataTable ExecuteQuery()
		{
			SPList list = SPContext.Current.Web.Lists[ListTitle];
			int limitCount = 0;
			foreach (SPListItem item in list.Items)
			{
				if (limitCount == RowLimit)
				{
					break;
				}

				DataRow row = _resultsTable.NewRow();
				foreach (string field in ViewFields)
				{
					row[field] = item.GetFormattedValue(field);
				}
				_resultsTable.Rows.Add(row);

				limitCount++;
			}

			return _resultsTable;
		}
	}
}
